package com.lc.luzhengtang.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.activity.ConfirmOrderActivity;
import com.lc.luzhengtang.activity.LoginActivity;
import com.lc.luzhengtang.adapter.ShoppingCartAdapter2;
import com.lc.luzhengtang.bean.CommenBean;
import com.lc.luzhengtang.bean.ShopCarListBean;
import com.lc.luzhengtang.conn.ConnClearShopCar;
import com.lc.luzhengtang.conn.ConnDeleteShopCar;
import com.lc.luzhengtang.conn.ConnShopCar;
import com.lc.luzhengtang.conn.GetUpdateCartGoodsNum;
import com.lc.luzhengtang.util.LovelyToast;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/2.
 */

public class ShoppingFragment2 extends BaseFragment3 implements View.OnClickListener
        , ShoppingCartAdapter2.CheckInterface, ShoppingCartAdapter2.ModifyCountInterface, ShoppingCartAdapter2.OnChooseClickListener, SwipeRefreshLayout.OnRefreshListener {
    public TextView tv_title, tv_settlement, tv_show_price;
    private TextView tv_all_check;
    private CheckBox ck_all;
    private ListView list_shopping_cart;
    private ShoppingCartAdapter2 shoppingCartAdapter;
    private TextView tv_edit;
    private boolean flag = false;
    private List<ShopCarListBean.DataBeanX.DataBean> shoppingCartBeanList = new ArrayList<>();
    private boolean mSelect;
    private double totalPrice = 0.00;// 购买的商品总价
    private int totalCount = 0;// 购买的商品总数量
    /**
     * 批量模式下，用来记录当前选中状态
     */
    private SparseArray<Boolean> mSelectState = new SparseArray<Boolean>();

    BigDecimal bd;

    private TextView iv_search;
    SwipeRefreshLayout swipeLayout;


    public String num_shop;

    LinearLayout layout_no_login;
    private Button btn_wuliu;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_shopcar2, null);

//        initData();
        initView(view);
        if (TextUtils.isEmpty(BaseApplication.basePreferences.readUid())) {
            iv_search.setVisibility(View.GONE);
        } else {
            iv_search.setVisibility(View.VISIBLE);
        }
        onRefresh();
        return view;
    }

    protected void initView(View view) {

        list_shopping_cart = (ListView) view.findViewById(R.id.list_shopping_cart);

        ck_all = (CheckBox) view.findViewById(R.id.ck_all);
        ck_all.setOnClickListener(this);

        tv_show_price = (TextView) view.findViewById(R.id.tv_show_price);
        tv_settlement = (TextView) view.findViewById(R.id.tv_settlement);
        tv_settlement.setOnClickListener(this);
        tv_edit = (TextView) view.findViewById(R.id.tv_edit);
        tv_edit.setOnClickListener(this);
        iv_search = (TextView) view.findViewById(R.id.iv_search);
        iv_search.setOnClickListener(this);
        swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeLayout);
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(Color.rgb(47, 223, 189));
        layout_no_login = (LinearLayout) view.findViewById(R.id.layout_no_login);
        btn_wuliu = (Button) view.findViewById(R.id.btn_wuliu);
        btn_wuliu.setOnClickListener(this);
        if (TextUtils.isEmpty(BaseApplication.basePreferences.readUid())) {
     /*   layout_no_login= (LinearLayout) view.findViewById(R.id.layout_no_login);
        btn_wuliu= (Button) view.findViewById(R.id.btn_wuliu);*/
            layout_no_login.setVisibility(View.VISIBLE);
            list_shopping_cart.setVisibility(View.GONE);
            swipeLayout.setVisibility(View.GONE);
        } else {
            layout_no_login.setVisibility(View.GONE);
            list_shopping_cart.setVisibility(View.VISIBLE);
            swipeLayout.setVisibility(View.VISIBLE);
        }
        Log.d(BaseApplication.basePreferences.readUid(), "33333333333333333");
        Log.d(BaseApplication.basePreferences.readUid(), "33333333333333333");
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (TextUtils.isEmpty(BaseApplication.basePreferences.readUid())) {

        } else {
            onRefresh();
        }
    }


    @Override
    protected void initData() {


        //   shoppingCartAdapter.setShoppingCartBeanList(shoppingCartBeanList);

    }


    @Override
    public void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(BaseApplication.basePreferences.readUid())) {
            layout_no_login.setVisibility(View.VISIBLE);
            list_shopping_cart.setVisibility(View.GONE);
            swipeLayout.setVisibility(View.GONE);
        } else {
            layout_no_login.setVisibility(View.GONE);
            list_shopping_cart.setVisibility(View.VISIBLE);
            swipeLayout.setVisibility(View.VISIBLE);
//            initData();
            onRefresh();
        }

    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            //全选按钮
            case R.id.ck_all:
                if (shoppingCartBeanList.size() != 0) {
                    if (ck_all.isChecked()) {
                        for (int i = 0; i < shoppingCartBeanList.size(); i++) {
                            shoppingCartBeanList.get(i).setChoosed(true);
                            num_shop = String.valueOf(shoppingCartBeanList.get(i).getNumber());
                        }
                        shoppingCartAdapter.notifyDataSetChanged();
                    } else {
                        for (int i = 0; i < shoppingCartBeanList.size(); i++) {
                            shoppingCartBeanList.get(i).setChoosed(false);
                            num_shop = String.valueOf(shoppingCartBeanList.get(i).getNumber());
                        }
                        shoppingCartAdapter.notifyDataSetChanged();
                    }
                }
                statistics();
                break;
            case R.id.tv_edit:
                flag = !flag;
                if (flag) {
                    tv_edit.setText("完成");
                    shoppingCartAdapter.isShow(false);
                } else {
                    tv_edit.setText("编辑");
                    shoppingCartAdapter.isShow(true);
                }
                break;

            case R.id.tv_settlement:
                StringBuilder sb = new StringBuilder();
                for (int r = 0; r < shoppingCartBeanList.size(); r++) {

                    if (shoppingCartBeanList.get(r).isChoosed()) {

                        sb.append(shoppingCartBeanList.get(r).getId());

                        sb.append(",");
                    }
                }

                if (sb.length() < 1) {
                    LovelyToast.makeText(getActivity(), "请选择商品", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else {

                    sb.deleteCharAt(sb.length() - 1);
                    String id = sb.toString();

                    Intent intent = new Intent();
                    intent.putExtra("cart_id", id);
                    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                    String OutString = bd.toString();

                    Log.d(OutString, "333333333333333333333333");
                    intent.putExtra("bd", OutString);
//                        num_shop

                    intent.putExtra("num_shop", num_shop);
                    intent.setClass(getActivity(), ConfirmOrderActivity.class);
                    startActivity(intent);
//                    ck_al
                    ck_all.setChecked(false);
//                    getActivity().finish();
                }

                break;

            case R.id.iv_search:

                clearData();
                break;

            case R.id.btn_wuliu:

                startActivity(new Intent(getActivity(), LoginActivity.class));
                break;

        }


    }

    public void clearData() {
        new ConnClearShopCar(BaseApplication.basePreferences.readUid(), new AsyCallBack<CommenBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                super.onSuccess(toast, type, o, commenBean);
                shoppingCartAdapter.notifyDataSetChanged();
                LovelyToast.makeText(getActivity(), commenBean.getMessage(), 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);

//                initData();
                onRefresh();
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }
        }


        ).execute(getActivity(), false);
    }


    /**
     * 单选
     *
     * @param position  组元素位置
     * @param isChecked 组元素选中与否
     */
    @Override
    public void checkGroup(int position, boolean isChecked) {

        shoppingCartBeanList.get(position).setChoosed(isChecked);

        if (isAllCheck())
            ck_all.setChecked(true);
        else
            ck_all.setChecked(false);

        shoppingCartAdapter.notifyDataSetChanged();
        statistics();


    }


    /**
     * 遍历list集合
     *
     * @return
     */
    private boolean isAllCheck() {

        for (ShopCarListBean.DataBeanX.DataBean group : shoppingCartBeanList) {
            if (!group.isChoosed())
                return false;
        }
        return true;
    }

    private double zong = 0.00;

    private Double falseTotalpirce = 0.00;
    private Double totalpirce;

    /**
     * 统计操作
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作
     * 3.给底部的textView进行数据填充
     */
    public void statistics() {


        zong = 0.00;
        falseTotalpirce = 0.00;
        for (int i = 0; i < shoppingCartBeanList.size(); i++) {
            if (shoppingCartBeanList.get(i).isChoosed()) {

                totalpirce = Double.valueOf(shoppingCartBeanList.get(i).getSales().toString()) * Double.valueOf(shoppingCartBeanList.get(i).getNumber());

                zong = zong + totalpirce - falseTotalpirce;

                num_shop = String.valueOf(shoppingCartBeanList.get(i).getNumber());
            } else {
                tv_show_price.setText("合计：¥ 0.00");
            }
        }

        bd = new BigDecimal(zong);

        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);

        tv_show_price.setText("合计：¥ " + bd);
    }

    /**
     * 增加
     *
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doIncrease(int position, View showCountView, boolean isChecked) {
        ShopCarListBean.DataBeanX.DataBean shoppingCartBean = shoppingCartBeanList.get(position);
        int currentCount = shoppingCartBean.getCount();
        currentCount++;
        shoppingCartBean.setCount(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }

    /**
     * 删减
     *
     * @param position      组元素位置
     * @param showCountView 用于展示变化后数量的View
     * @param isChecked     子元素选中与否
     */
    @Override
    public void doDecrease(int position, View showCountView, boolean isChecked) {
        ShopCarListBean.DataBeanX.DataBean shoppingCartBean = shoppingCartBeanList.get(position);
//        int currentCount = shoppingCartBean.getCount();
        int currentCount = shoppingCartBeanList.size();
        if (currentCount == 1) {
            return;
        }
        currentCount--;
        shoppingCartBean.setCount(currentCount);
        ((TextView) showCountView).setText(currentCount + "");
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();

    }

    /**
     * 删除
     *
     * @param position
     */
    @Override
    public void childDelete(int position) {
        shoppingCartBeanList.remove(position);
        shoppingCartAdapter.notifyDataSetChanged();
        statistics();
    }

    @Override
    public void onChooseClick(final View view) {
        switch (view.getId()) {
            case R.id.ib_up:

                if (shoppingCartBeanList.get((Integer) view.getTag()).isChoosed) {

                    int i = shoppingCartBeanList.get((Integer) view.getTag()).getNumber() + 1;
                    Log.d("onChooseClick", "i = " + i);
//                Toast.makeText(getActivity(), "增加成功", Toast.LENGTH_SHORT).show();
                    new GetUpdateCartGoodsNum(BaseApplication.basePreferences.readUid(), shoppingCartBeanList.get(((int) view.getTag())).getId() + "", String.valueOf(i), new AsyCallBack<CommenBean>() {

                        @Override
                        public void onSuccess(String toast, int type, CommenBean info) throws Exception {
                            super.onSuccess(toast, type, info);
                            ShopCarListBean.DataBeanX.DataBean shopCarBean = shoppingCartBeanList.get((Integer) view.getTag());
//                        ShopCarBean shopCarBean = list.get(((int) view.getTag()));
                            String number = shopCarBean.getNumber() + "";
                            int i1 = Integer.parseInt(number);

                            i1++;
                            shoppingCartBeanList.get(((int) view.getTag())).setNumber(i1);
                            zong = 0.00;
                            int size1 = shoppingCartBeanList.size();

                            for (int i = 0; i < size1; i++) {
                                if (shoppingCartBeanList.get(i).isChoosed()) {

                                    totalpirce = Double.valueOf(shoppingCartBeanList.get(i).getSales().toString()) * Double.valueOf(shoppingCartBeanList.get(i).getNumber());

                                    num_shop = String.valueOf(shoppingCartBeanList.get(i).getNumber());
                                    zong = zong + totalpirce;

                                } else {

                                    tv_show_price.setText("合计：¥ 0.00");
                                }
                            }

                            bd = new BigDecimal(zong);
                            bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                            tv_show_price.setText("合计：¥ " + bd);
                            shoppingCartAdapter.notifyDataSetChanged();
//                            onRefresh();
                        }


                        @Override
                        public void onFail(String toast, int type) throws Exception {
                            super.onFail(toast, type);
                            UtilToast.show(getContext(), "库存不足");

                        }

                        @Override
                        public void onEnd(String toast, int type) throws Exception {
                            super.onEnd(toast, type);
                            shoppingCartAdapter.notifyDataSetChanged();

                        }
                    }).execute(getContext());
                } else {
//                    Toast.makeText(getActivity(), "只能修改已选中的商品", Toast.LENGTH_SHORT).show();
                    LovelyToast.makeText(getActivity(), "只能修改已选中的商品", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                }


                break;

            case R.id.ib_down:

                if (shoppingCartBeanList.get((Integer) view.getTag()).isChoosed) {
                    int i2 = shoppingCartBeanList.get((Integer) view.getTag()).getNumber() - 1;
                    if (i2<1){
                        LovelyToast.makeText(getActivity(), "数量不能小于1", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }else {
                        //                Toast.makeText(getActivity(), "增加成功", Toast.LENGTH_SHORT).show();
                        new GetUpdateCartGoodsNum(BaseApplication.basePreferences.readUid(), shoppingCartBeanList.get(((int) view.getTag())).getId() + "", String.valueOf(i2), new AsyCallBack<CommenBean>() {

                            @Override
                            public void onSuccess(String toast, int type, CommenBean info) throws Exception {
                                super.onSuccess(toast, type, info);
                                ShopCarListBean.DataBeanX.DataBean shopCarBean = shoppingCartBeanList.get((Integer) view.getTag());
//                        ShopCarBean shopCarBean = list.get(((int) view.getTag()));

                                String number = shopCarBean.getNumber() + "";

                                int i1 = Integer.parseInt(number);
                                if (i1 < 2) {
                                    LovelyToast.makeText(getActivity(), "数量不能小于1", 0, LovelyToast
                                            .SUCCESS, LovelyToast.SCALE);
                                } else {

                                    i1--;
                                    shoppingCartBeanList.get(((int) view.getTag())).setNumber(i1);
                                    zong = 0.00;
                                    int size1 = shoppingCartBeanList.size();

                                    for (int i = 0; i < size1; i++) {
                                        if (shoppingCartBeanList.get(i).isChoosed()) {

                                            totalpirce = Double.valueOf(shoppingCartBeanList.get(i).getSales().toString()) * Double.valueOf(shoppingCartBeanList.get(i).getNumber());

                                            num_shop = String.valueOf(shoppingCartBeanList.get(i).getNumber());
                                            zong = zong + totalpirce;

                                        } else {

                                            tv_show_price.setText("合计：¥ 0.00");
                                        }
                                    }

                                    bd = new BigDecimal(zong);
                                    bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    tv_show_price.setText("合计：¥ " + bd);
                                }
                                shoppingCartAdapter.notifyDataSetChanged();
//                            onRefresh();
                            }


                            @Override
                            public void onFail(String toast, int type) throws Exception {
                                super.onFail(toast, type);
                                UtilToast.show(getContext(), "库存不足");

                            }

                            @Override
                            public void onEnd(String toast, int type) throws Exception {
                                super.onEnd(toast, type);

                                shoppingCartAdapter.notifyDataSetChanged();

                            }
                        }).execute(getContext());
                    }




                } else {
//                    Toast.makeText(getActivity(), "只能修改已选中的商品", Toast.LENGTH_SHORT).show();
                    LovelyToast.makeText(getActivity(), "只能修改已选中的商品", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                }


                break;


            case R.id.img_delete:
                new ConnDeleteShopCar(BaseApplication.basePreferences.readUid(), shoppingCartBeanList.get(((int) view.getTag())).getId() + "", new AsyCallBack<CommenBean>() {
                    @Override
                    public void onStart(int type) throws Exception {
                        super.onStart(type);
                    }

                    @Override
                    public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                        super.onSuccess(toast, type, o, commenBean);
                        LovelyToast.makeText(getActivity(), commenBean.getMessage(), 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                        //     getData();
                        shoppingCartBeanList.remove((int) view.getTag());
                        shoppingCartAdapter.notifyDataSetChanged();

                        statistics();

                      /*  totalpirce = Double.valueOf(shoppingCartBeanList.get(i).getMarket_price().toString()) * Double.valueOf(shoppingCartBeanList.get(i).getNumber());

                        zong = zong + totalpirce - falseTotalpirce;

                        num_shop = String.valueOf(shoppingCartBeanList.get(i).getNumber());
                    } else {
                        tv_show_price.sText("合计：¥ 0.00");*/

//                        shoppingCartBeanList.get((int) view.getTag()).getMarket_price().toString()) * Double.valueOf(shoppingCartBeanList.get((int)view.getTag()).getNumber()

//                        tv_show_price.setText();

                    }


                    @Override
                    public void onFail(String toast, int type) throws Exception {
                        super.onFail(toast, type);
                    }

                    @Override
                    public void onEnd(String toast, int type) throws Exception {
                        super.onEnd(toast, type);
                    }
                }


                ).execute(getActivity(), false);

                break;


        }
    }

    @Override
    public void onRefresh() {
        new ConnShopCar(BaseApplication.basePreferences.readUid(), "1", new AsyCallBack<ShopCarListBean>() {
            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
                showLoading();
            }

            @Override
            public void onSuccess(String toast, int type, Object o, final ShopCarListBean s) throws Exception {
                super.onSuccess(toast, type, o, s);

                shoppingCartBeanList.clear();
                shoppingCartBeanList.addAll(s.getData().getData());
                ck_all.setChecked(false);
                tv_show_price.setText("合计："+"¥" + "0.00");

                shoppingCartAdapter = new ShoppingCartAdapter2(getActivity(), shoppingCartBeanList);
//                shoppingCartAdapter.setOnNumChangListener(this);
                shoppingCartAdapter.setCheckInterface(ShoppingFragment2.this);
                shoppingCartAdapter.setModifyCountInterface(ShoppingFragment2.this);
                list_shopping_cart.setAdapter(shoppingCartAdapter);
                shoppingCartAdapter.setOnChooseClickListener(ShoppingFragment2.this);

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);

            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                dismissLoading();
                setRefreshing(false);
            }
        }

        ).execute(getActivity(), false);
    }

    public void setRefreshing(final boolean refreshing) {
        swipeLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeLayout.setRefreshing(refreshing);
            }
        });
    }

}
